import React, { useState } from "react";
import { Switch,Tag ,Spin,Checkbox,Form,message,Modal} from 'antd';
import {connect} from 'react-redux'
import {FormOutlined,EyeOutlined} from '@ant-design/icons'
import './index.scss'
import LlxForm from 'components/LlxForm/index'
import {editTask,configurationFollow,queryByBook,queryByIdAudioPublish,queryByIdVideoPublish,updateBatchPlanData} from 'api/index'
import {checkPublishData,addHistoryRouter} from 'redux/action'
import { withRouter } from "react-router-dom";
import PreviewVideo from 'components/LlxPreview/video'
import PreviewBook from 'components/LlxPreview/book'
import PreviewAudio from 'components/LlxPreview/audio'
import PreviewWordSubject from 'components/LlxPreview/afterPreview'
// import LookSubject from 'components/'
const EditTasks = (props) => {

  const {isModalVisible, setIsModalVisible,forms} = props


  const item = [
    {label: '目标单词',type:'textArea', name: 'targetWord' , span: 24 },
    {label: '目标句子',type:'textArea', name: 'targetSentence' , span: 24 },
]
  const handleOk = async() => {

     const data = {
      id: forms.getFieldValue().id,
      levelId:  forms.getFieldValue().levelId || 106,
      targetSentence:forms.getFieldValue().targetSentence,
      targetWord:forms.getFieldValue().targetWord,
     }

      await editTask(data)
      message.success('修改成功')
      props.getNewList()
      setIsModalVisible(false)

  }

  const handleCancel = () => {
    setIsModalVisible(false)
  }

  return   <Modal destroyOnClose width={700} title="修改任务" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
  <LlxForm form={forms} labelCol={5} formItem={item} />
</Modal>
}

function PlanSubject(props) {
  
  const {getNewList} = props

  const [isModalVisible,setIsModalVisible] = useState(false)
  const [isModalVisiblePreivew,setIsModalVisiblePreivew] = useState(false)
  const [isModalVisiblePreviewAudio,setIsModalVisiblePreviewAudio] = useState(false)
  const [isModalVisiblePreviewTheme,setIsModalVisiblePreviewTheme] = useState(false)
  const [previewStudy,setPreviewStudy] = useState(false)
  const [isModalVisiblePreivewBook,setIsModalVisiblePreivewBook] = useState(false)
  // const [isModalVisibleLook,setIsModalVisibleLook] = useState(false)
  const [items,setItems] = useState({})
  const {data=[],loading} = props
  const [forms] = Form.useForm()

  const onChangeRead = async(e,y) => {
    const data = {
      follow: y.follow === 0 ? 1 : 0,
      id: y.id
    }
    try {
      const res = await configurationFollow(data)
      message.success(res.message)
      getNewList()
    } catch (err) {
      console.log(err)
    } finally {
      getNewList()
    }
  }
  const onChangeTask = (e,x) => {
    x.checkTask = e.target.checked
  }
  const onChangeLink = (e,x) => {
    x.checkLink = e.target.checked
  }
  const editTask = (x) => {
    forms.setFieldsValue(x)

    setIsModalVisible(true)
  }
  // 4.去详情
const goInfo =(value)=>{
  props.checkPublishDataBtn()
  switch(value.type) {
    case 'LESSON':
      props.history.push('/view/plan/themeSubjectInfo?id=' + value.dataId)
      props.addRouter({
        menuName:'主题课详情',url:'plan/themeSubjectInfo?id=' + value.dataId 
      })
    break
    case 'VIDEO':
      props.history.push('/view/video/videoInfo?id=' + value.dataId)
      props.addRouter({
        menuName:'视频详情',url:'video/videoInfo?id=' + value.dataId 
      })
    break
    case 'PAPER':
      props.history.push('/view/test/testPaperInfo?id=' + value.dataId)
      props.addRouter({
        menuName:'试卷详情',url:'test/testPaperInfo?id=' + value.dataId 
      })
    break
    case 'WORD':
      props.history.push('/view/word/wordInfo?id=' + value.dataId)
      props.addRouter({
        menuName:'单词详情',url:'word/wordInfo?id=' + value.dataId 
      })
    break
    case 'IR_BOOK':
      props.history.push('/view/book/intensiveBookInfo?id=' + value.dataId)
      props.addRouter({
        menuName:'精读书详情',url:'book/intensiveBookInfo?id=' + value.dataId 
      })
    break
    case 'BOOK':
      props.history.push('/view/book/bookInfo?id=' + value.dataId)
      props.addRouter({
        menuName:'泛读详情',url:'book/bookInfo?id=' + value.dataId 
      })
    break
    case 'ALBUM_VIDEO':
      props.history.push('/view/video/videoAlbumInfo?id=' + value.dataId)
      props.addRouter({
        menuName:'专辑详情',url:'video/videoAlbumInfo?id=' + value.dataId 
      })
    break
    case 'SONG':
      props.history.push('/view/audio/audioInfo?id=' + value.dataId)
      props.addRouter({
        menuName:'音频详情',url:'audio/audioInfo?id=' + value.dataId 
      })
    break
    default:
      return
    }
} 
// 5.预览
const previewdata = async(value) => {
  switch(value.type) {
    case 'LESSON':
      setItems({
        id:value.dataId
      })
      setIsModalVisiblePreviewTheme(true)
    break
    case 'VIDEO':
      
      const res2 = await queryByIdVideoPublish(value.dataId)
      setItems({
        srtUrl:res2.result.videoSrt,
        videoUrl:res2.result.videoUrl
      })
      console.log({
        srtUrl:res2.result.videoSrt,
        videoUrl:res2.result.videoUrl
      });
      setIsModalVisiblePreivew(true)
    break
    case 'LE_VIDEO':
      setItems({
        id:value.dataId
      })
      setPreviewStudy(true)
    break
    case 'IR_BOOK':
      const res = await queryByBook(value.dataId)
      setItems({
        id:res.result.bookId + '?' + Math.random()*100
      })
      setIsModalVisiblePreivewBook(true)
    break
    case 'BOOK':
      setItems({
        id:value.dataId + '?' + Math.random()*100
      })
      setIsModalVisiblePreivewBook(true)
    break
    case 'SONG':
      const res1 = await queryByIdAudioPublish(value.dataId)
      setItems({
        srtUrl:res1.result.songSrt,
        audioUrl:res1.result.audioUrl
      })
      setIsModalVisiblePreviewAudio(true)
    break
    default:
      return
    }
}

// 
const goTop = async(a,i) => {
       const index = a.linkList.findIndex(x => x.id === i.id)
      await updateBatchPlanData([{ id: a.linkList[index - 1].id, serialNumber: a.linkList[index - 1].serialNumber + 1 }, { id: a.linkList[index].id, serialNumber: a.linkList[index].serialNumber - 1 }])
      getNewList()
}
  
const goBottom =async(a,i) => {
  const index = a.linkList.findIndex(x => x.id === i.id)
  await updateBatchPlanData([{ id: a.linkList[index + 1].id, serialNumber: a.linkList[index + 1].serialNumber - 1 }, { id: a.linkList[index].id, serialNumber: a.linkList[index].serialNumber + 1 }])
  this.getNewList()
}
  
  return <div>
        <div className="table-list">
        <Spin tip="Loading..." spinning={loading}>
          <div className="table">
            <table>
              <thead>
                <tr>
                  <th>
                    任务</th>
                  <th style={{width:'100px'}}>用户级别</th>

                  <th>目标单词</th>
                  <th>目标句子</th>
                  <th style={{width:'100px'}}>
                    环节序号
                  </th>
                  <th>环节名称</th>
                  <th>文件名称</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
               {
                 data.map((x,j)=> {
                   return <>
                   <tr key={j}>
                         <td rowSpan={x.linkList.length+1}>
                           {
                               props.examineStatus?'':<Checkbox onChange={(e)=>onChangeTask(e,x)}></Checkbox>
                           }
                           &nbsp;&nbsp;
                           {x.serialNumber}&nbsp;&nbsp;

                           {
                               props.examineStatus?'':<FormOutlined className="plan-icon" onClick={()=>editTask(x)}/>
                           }
                           &nbsp;&nbsp;
                           <EyeOutlined className="plan-icon"/>

                         </td>
                         <td rowSpan={x.linkList.length+1} style={{width:'100px'}}>
                           {x.levelAppName}
                         </td>
                         <td rowSpan={x.linkList.length+1}>
                           {x.targetWord}
                         </td>
                         <td rowSpan={x.linkList.length+1}>
                           {x.targetSentence}
                         </td>
                   </tr>
                   {
                     x.linkList.map((k,p)=>{
                       return <tr key={k.id}>
                       <td  style={{width:'100px'}}>
                          {
                               props.examineStatus?'':<Checkbox onChange={(e)=>onChangeLink(e,k)}></Checkbox>
                           }
                           &nbsp;&nbsp;
                         {k.serialNumber}</td>
                       <td>
                         {k.taskTypeName}
                         {
                           ['拓展绘本','视频学习','拓展视频'].includes(k.taskTypeName)?<Switch disabled={props.examineStatus}  checkedChildren="跟读" unCheckedChildren="" onChange={(e)=>onChangeRead(e,k)} size="small" checked={k.follow===1} />:''
                         }
                       </td>
                       <td>
                         {
                           k.upperLower===1000?<Tag color="error">下架</Tag>:(
                            k.upperLower===1010?<Tag color="success">上架</Tag>:<Tag color="warning">未知</Tag>
                           )
                         }
                        
                       
                         <span className="text-link" onClick={()=>goInfo(k)}>{k.fileName}</span>
                       </td>
                       <td>
                         
                          <span className="text-link" onClick={()=>previewdata(k)}>预览</span>&nbsp;&nbsp;
                          {
                            props.examineStatus?'':<>
                            {
                            p===0?'':<span onClick={()=>goTop(x,k)} className="text-link">上移</span>
                          }
                          &nbsp;&nbsp;
                          {
                            p===x.linkList.length-1?'':<span onClick={()=>goBottom(x,k)} className="text-link">下移</span>
                          }
                            </>
                          }
                          
                       </td>
                       </tr>
                     })
                   }
                   </>
                 })
               }
              </tbody>
            </table>
          </div>
          </Spin>
        </div>


        <EditTasks getNewList={getNewList} setIsModalVisible={setIsModalVisible} isModalVisible={isModalVisible} forms={forms}></EditTasks>


      {/* <LookSubject setIsModalVisible={setIsModalVisibleLook} isModalVisible={isModalVisibleLook}></LookSubject> */}

      <PreviewVideo prevewVideo={items}  isModalVisible={isModalVisiblePreivew} setIsModalVisible={setIsModalVisiblePreivew}></PreviewVideo>

      <PreviewAudio prevewAudio={items} isModalVisible={isModalVisiblePreviewAudio} setIsModalVisible={setIsModalVisiblePreviewAudio} ></PreviewAudio>
    
       {/* 预览 */}
       <PreviewWordSubject type={'theme'} id={items.id} isModalVisible={isModalVisiblePreviewTheme} setIsModalVisible={setIsModalVisiblePreviewTheme}></PreviewWordSubject>
   

       {/* 预览学习视频 */}
       <PreviewWordSubject type={'study'} id={items.id}  isModalVisible={previewStudy} setIsModalVisible={setPreviewStudy}></PreviewWordSubject>

      <PreviewBook id={items.id}  isModalVisible={isModalVisiblePreivewBook} setIsModalVisible={setIsModalVisiblePreivewBook}></PreviewBook>
  </div>
}
const mapDispatchToProps = (dispatch) => {
  return {
    checkPublishDataBtn: () => dispatch(checkPublishData()),
    addRouter: (route) => dispatch(addHistoryRouter(route)),
  }
}


export default connect((state)=>{
  return {userBtnRole:state.userBtnRole,tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(withRouter(PlanSubject))
